package szcg.scheduled.service.impl.ydcg;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import szcg.scheduled.service.entity.ydcg.CaseBean;
import szcg.scheduled.service.service.ydcg.PushCaseService;

import java.util.List;

@Service
public class PushCaseServiceImpl implements PushCaseService {
    private static final Logger logger = LoggerFactory.getLogger(PushCaseServiceImpl.class);

    private static final String qycg = "www.qysszhcsglzhzx.cn";

    @Qualifier("OkHttpClient")
    private final OkHttpClient okHttpClient;

    public PushCaseServiceImpl(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @Override
    public void push(CaseBean caseBean) {
        String AddOrUpdateUrl = "https://" + qycg + "/oboe/admin/third/bakevent/addEvent.jhtml";
        //原始案件号
        String originalEventCode = caseBean.eventcode;
        //数据预处理
        handle(caseBean);
        //构建请求体
        MultipartBody body = new MultipartBody.Builder()//
                .addFormDataPart("eventCode", caseBean.eventcode)//案件编号
                .addFormDataPart("eventDesc", caseBean.eventDesc)//案件描述
                .addFormDataPart("status", caseBean.status)//案件状态字典
                .addFormDataPart("eventClass", caseBean.eventClass)//案件分类字典（默认值010901）
                .addFormDataPart("eventTime", caseBean.eventTime)//案件发生时间 yyyy-MM-dd HH:mm:ss
                .addFormDataPart("locationDesc", caseBean.locationDesc)//案件发生地址
                .addFormDataPart("currentStepName", caseBean.currentStepName)//当前环节名称(中文名称)
                .addFormDataPart("currentDeptName", caseBean.currentDeptName)//当前环节处理部门(中文名称)
                .addFormDataPart("currentDealPeopleName", caseBean.currentDealPeopleName)//当前环节处理人(中文名称)
                .addFormDataPart("fileUrls", caseBean.fileUrls)//图片链接（多个链接以英文逗号分隔）
                .build();

        //创建post请求
        Request request = new Request.Builder()//
                .addHeader("Cookie", getCookie())//添加cookie
                .addHeader("Content-Type", "multipart/form-data")//添加请求类型
                .url(AddOrUpdateUrl)//请求连接
                .post(body)//请求体
                .build();//构建

        try (Response response = okHttpClient.newCall(request).execute()) {
            //同步请求
            ResponseBody resBody = response.body();
            if (resBody == null) {
                String errMsg = "onResponse为null！！ ";
                logger.error(errMsg);
                return;
            }
            //800200：推送成功
            String string = resBody.string();
            logger.warn("案件：{}--->onResponse: {}", originalEventCode, string);
        } catch (Exception e) {
            String message = e.getMessage();
            logger.error("推送异常：Exception: {}", message);
        }
    }

    private String getCookie() {
        //获取cookies
        String UserAccount = "V9f3MA6zrw4EgCKhCqZ0Mg==";
        String UserPassword = "gb48S6zqJOCbG5hoMYbrDQ==";
        String LoginUrl = "https://" + qycg + "/oboe/login/login/thirdLogin.jhtml";
        String CookieUrl = LoginUrl + "?" + "userAccount=" + UserAccount + "&" + "userPassword=" + UserPassword;
        Request request = new Request.Builder().url(CookieUrl).build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody body = response.body();
            if (body == null) {
                logger.error("获取cookie失败：body为空");
                return "";
            }
            String res = body.string();
            if (res.contains("true")) {
                //登陆成功
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                if (!cookies.isEmpty()) {
                    String s = cookies.get(0);
                    String[] s1 = s.trim().replaceAll(" ", "").split(";");
                    return s1[0];
                } else {
                    logger.error("获取cookie为空");
                }
            } else {
                //登陆失败
                logger.error("获取cookie失败（非登录状态）：ResponseBody:{}", res);
            }
        } catch (Exception e) {
            logger.error("获取cookie失败：Exception:{}", e.getMessage());
        }
        return "";
    }

    //数据预处理
    private static void handle(CaseBean caseBean) {
        if (caseBean.eventcode == null) {
            caseBean.eventcode = "";
        }
        if (caseBean.eventDesc == null) {
            caseBean.eventDesc = "";
        }
        if (caseBean.status == null) {
            caseBean.status = "";
        }
        if (caseBean.eventClass == null) {
            caseBean.eventClass = "";
        }
        if (caseBean.eventTime == null) {
            caseBean.eventTime = "";
        }
        if (caseBean.locationDesc == null) {
            caseBean.locationDesc = "";
        }
        if (caseBean.currentStepName == null) {
            caseBean.currentStepName = "";
        }
        if (caseBean.currentDeptName == null) {
            caseBean.currentDeptName = "";
        }
        if (caseBean.currentDealPeopleName == null) {
            caseBean.currentDealPeopleName = "";
        }
        if (caseBean.fileUrls == null) {
            caseBean.fileUrls = "";
        }
        //案件号前面加id
        caseBean.eventcode = "YD" + caseBean.eventcode;
        //日期格式化
        caseBean.eventTime = caseBean.eventTime.replaceAll("T", " ");
    }


}
